<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        title="警告：只允许为第三级别分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row>
        <span>选择商品分类：</span>
        <!-- 级联选择器 -->
        <el-cascader
          v-model="selectParmsKeys"
          :options="cartList"
          :props="porps"
          @change="handleChange"
        ></el-cascader>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            class="addMargin"
            type="primary"
            :disabled="isbtnOk"
            @click="addFormDialog()"
            >添加参数</el-button
          >
          <!--动态Table表格区域  -->
          <el-table :data="manyTableList" style="width: 100%" border>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleclose(i,scope.row)"
                  >{{ item }}
                </el-tag>
                <!-- 动态编辑标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>

            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="showDelDialog(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <el-button
            class="addMargin"
            type="primary"
            :disabled="isbtnOk"
            @click="addFormDialog()"
            >添加属性</el-button
          >
          <!--静态Table表格区域  -->
          <el-table :data="onlyTabelList" style="width: 100%" border>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleclose(i,scope.row)"
                  >{{ item }}
                </el-tag>
                <!-- 动态编辑标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"> </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="showDelDialog(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数/属性对话框 -->
    <!-- title需要动态绑定 -->
    <el-dialog
      :title="'添加' + this.AttributeOrParameter"
      :visible.sync="addFormDialogVisible"
      width="50%"
      @close="addClosed()"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRefs"
        label-width="100px"
      >
        <el-form-item :label="AttributeOrParameter" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addFormDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamForm()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 点击编辑 -->
    <!-- title需要动态绑定 -->
    <el-dialog
      :title="'修改' + this.AttributeOrParameter"
      :visible.sync="editFormDialogVisible"
      width="50%"
      @close="editClosed()"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRefs"
        label-width="100px"
      >
        <el-form-item :label="AttributeOrParameter" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editFormDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamForm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 存放级联选择器数据
      cartList: [],
      //   级联选择器数组用于
      selectParmsKeys: [],
      //   配置级联选择器规则
      porps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //   标签页默认选择
      activeName: "many",
      //   动态参数数据
      manyTableList: [],
      //   静态参数数据
      onlyTabelList: [],
      //  添加参数/属性对话框是否显示
      addFormDialogVisible: false,
      addForm: {
        attr_name: "",
      },
      //  编辑参数/属性对话框是否显示
      editForm: {
        attr_name: "",
      },
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },
      // 控制编辑对话框是否显示
      editFormDialogVisible: false,
      editFormRules: {
        attr_name: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },
      // 文本框与按钮的切换
      inputVisible: false,
      // 文本框中的值
      inputValue: "",
    };
  },
  created() {
    this.getCartList();
  },
  methods: {
    // 获取级联选择框数据
    async getCartList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$Message.error("获取级联选择框数据失败");
      }
      this.cartList = res.data;
      console.log(this.cartList);
    },
    // 标签页 点击事件
    handleClick() {
      this.getParmsList();
      console.log(this.selectParmsKeys);
    },
    // 级联选择框参数改变时候 获取参数数据
    handleChange() {
      this.getParmsList();
    },
    //  获取参数数据
    async getParmsList() {
      if (this.selectParmsKeys.length !== 3) {
        this.selectParmsKeys = [];
        this.onlyTabelList = [];
        this.manyTableList = [];
        return;
      }
      console.log(this.selectParmsKeys);
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      console.log(res.data);
      res.data.forEach((item) => {
       item.attr_vals= item.attr_vals !== ""
          ? (item.attr_vals = item.attr_vals.split(" ")): [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (res.meta.status !== 200) {
        return this.$Message.error("获取参数列表失败");
      }
      console.log(res.data);
      if (this.activeName === "many") {
        this.manyTableList = res.data;
      } else {
        this.onlyTabelList = res.data;
      }
    },
    // 监听添加参数
    addFormDialog() {
      this.addFormDialogVisible = true;
    },
    // 监听 对话框确定按钮
    addParamForm() {
      // this.addFormDialogVisible = false;
      // 表单预验证
      this.$refs.addFormRefs.validate(async (valid) => {
        //   console.log(valid);
        if (!valid) return;
        // 添加动态参数或者静态属性
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: this.attr_vals,
          }
        );
        console.log(res.data);
        if (res.meta.status !== 201) {
          this.$Message.error("添加参数失败");
          this.addFormDialogVisible = false;
          console.log(res.data);
        } else {
          this.$Message.success("添加参数成功");
          this.getParmsList();
          this.addFormDialogVisible = false;
        }
      });
    },
    // 关闭添加参数关闭 对话框清空
    addClosed() {
      this.$refs.addFormRefs.resetFields();
    },

    // 点击编辑展示对话框
    async showEditDialog(attr_id) {
      // 获取id根据 ID 查询参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      );
      if (res.meta.status !== 200) {
        this.$Message.error("获取数据失败");
        // this.editFormDialogVisible = false;
        console.log(res.data);
      } else {
        this.$Message.success("获取数据成功");
        this.editForm = res.data;
      }
      this.editFormDialogVisible = true;
    },
    // 关闭对话框的时候,清空数据
    editClosed() {
      this.$refs.editFormRefs.resetFields();
    },
    // 监听 点击编辑显示的对话框的确定按钮
    async editParamForm() {
      // this.editFormDialogVisible = false;
      // 表单预验证
      this.$refs.editFormRefs.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;
        // 添加动态参数或者静态属性
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        );
        console.log(res.data);
        if (res.meta.status !== 200) {
          this.$Message.error("修改参数失败");
          // this.editFormDialogVisible = false;
          console.log(res.data);
        } else {
          this.$Message.success("修改参数成功");
          this.getParmsList();
          this.editFormDialogVisible = false;
        }
      });
    },
    // 监听删除事件
    async showDelDialog(attrid) {
      const resconfirm = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(resconfirm);
      if (resconfirm !== "confirm") {
        return this.$Message.info("已取消删除");
      }
      // this.$Message.info("已取消删除1")
      // 刷新数据关闭dialog
      // this.getCartList();
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attrid}`
      );
      if (res.meta.status !== 200) {
        return this.$Message.error("删除失败！");
      }
      this.getParmsList();
      this.$Message.success("删除成功！");
    },
    // new Tage处理事件
    async handleInputConfirm(row) {
      // console.log("ok");
      // 去除空格
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      // 没有return   进行后续操作(只在前端渲染，没有加入数据库)
      //  row.attr_vals
      console.log(row.attr_vals);
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      // . 编辑提交参数
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      console.log(res);
      if (res.meta.status !== 200) {
        this.$Message.error("提交参数失败");
        // this.editFormDialogVisible = false;
        // console.log(res.data);
      } else {
        this.$Message.success("提交参数成功");
        // this.editForm = res.data;
      }
    },
    // 将小标签提交到数据库
    async saveAttr(row){
      // . 编辑提交参数
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      console.log(res);
      if (res.meta.status !== 200) {
        this.$Message.error("提交参数失败");
        // this.editFormDialogVisible = false;
        // console.log(res.data);
      } else {
        this.$Message.success("提交参数成功");
        // this.editForm = res.data;
      }
    },
    showInput(row) {
      row.inputVisible = true;
      //$ nextTck 当页面渲染完成后才会调用回调函数
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 关闭小标签
    handleclose(i,row){
      row.attr_vals.splice(i,1)
      this.saveAttr(row)
    }
    
  },
  computed: {
    //   判断按钮是否禁用
    isbtnOk() {
      if (this.selectParmsKeys.length !== 3) {
        return true;
      }
      return false;
    },
    //   当前选中的三级id
    cateId() {
      if (this.selectParmsKeys.length === 3) {
        return this.selectParmsKeys[2];
      }
      return null;
    },
    AttributeOrParameter() {
      if (this.activeName === "many") {
        return "动态参数";
      } else {
        return "静态参数";
      }
    },
  },
};
</script>

<style scoped>
.el-alert {
  margin: 15px 0;
}
.addMargin {
  margin: 15px 0;
}
.el-tag {
  margin-left: 10px;
}
.input-new-tag {
  width: 90px;
  margin-left: 15px;
  vertical-align: bottom;
}
.button-new-tag{
  margin-left: 15px;
}
</style>